<?php

/**
 * Created by PhpStorm.
 * User: 31772
 * Date: 2017/4/12
 * Time: 15:23
 */
class Db
{
    private $connect;
    private $table;
    private $name = "*";
    private $where = "1=1";
    private $query;
    private $value;
    private static $my = NULL;
    public function __construct()
    {
        $database = require_once "config.php";
        $database = $database['database'];
        $this->connect = mysqli_connect($database['ip'],$database['root'],$database['password'],$database['name'],$database['port']);
        mysqli_query($this->connect,"name set ".$database['code']);
    }
    public function table($table){
        $this->table = $table;
        return $this;
    }
    public function where($where){
        $this->where = $where;
        return $this;
    }
    public function name($name){
        $this->name = $name;
        return $this;
    }
    public function value($value){
        $this->value = $value;
        return $this;
    }
    public function select(){
        $sql = "select ".$this->name." from ".$this->table." where ".$this->where;
        $this->query($sql);
        return $this->all();
    }
    public function one(){
        $sql = "select ".$this->name." from ".$this->table." where ".$this->where;
        $this->query($sql);
        return mysqli_fetch_assoc($this->query);
    }
    public function query($sql){
        $this->query = mysqli_query($this->connect,$sql);
        $this->emptydate();
        return $this;
    }
    public function insert(){
        $sql = "insert into ".$this->table."(".$this->name.") values (".$this->value.")";
        $this->query($sql);
        if($this->query)
            return mysqli_insert_id($this->connect);
        else
            return -1;
    }
    public function delete(){
        $sql = "delete from ".$this->table." where ".$this->where;
        $this->query($sql);
        return $this->query;
    }
    public function update(){
        $sql = "UPDATE ".$this->table." set ".$this->name." where ".$this->where;
        //echo $sql;
        $this->query($sql);
        return $this->query;
    }
    public function __destruct()
    {
        @mysqli_close($this->connect);
    }
    private function all(){
        $arr = [];
        while($value = mysqli_fetch_assoc($this->query)){
            $arr[] = $value;
        }
        return $arr;
    }
    public static function getDb(){
        self::$my = new Db();
        return self::$my;
    }
    private function emptydate(){
        $this->name = "*";
        $this->where = "1=1";
        $this->table = "";
        $this->value = "";
    }
}